package com.toocms.jinjuhang.ui.mine.my_favorite

import android.app.Application
import androidx.databinding.ObservableArrayList
import androidx.databinding.ObservableField
import com.toocms.jinjuhang.BR
import com.toocms.jinjuhang.R
import com.toocms.jinjuhang.config.Urls
import com.toocms.jinjuhang.config.UserRepository
import com.toocms.jinjuhang.data.center.MyCollGoodsData
import com.toocms.jinjuhang.widget.view_model.requestData
import com.toocms.tab.base.BaseModel
import com.toocms.tab.base.BaseViewModel
import com.toocms.tab.binding.ItemBinding
import com.toocms.tab.binding.command.BindingAction
import com.toocms.tab.binding.command.BindingCommand
import com.toocms.tab.bus.event.SingleLiveEvent

class MyFavoriteModel(application: Application) : BaseViewModel<BaseModel>(application) {
    private var p = 1

    val items = ObservableArrayList<MyFavoriteItemModel>()
    val itemBinding =
        ItemBinding.of<MyFavoriteItemModel>(BR.myFavoriteItemModel, R.layout.item_my_favorite)

    val stopRefreshOrLoadSingleLiveEvent = SingleLiveEvent<Unit>()

    val refreshBindingCommand = BindingCommand<BindingAction>(BindingAction {
        refresh(false)
    })

    val loadBindingCommand = BindingCommand<BindingAction>(BindingAction {
        load()
    })


    init {
        refresh(true)
    }

    private fun refresh(isShowLoading: Boolean = false) {
        p = 1
        myCollGoods(p, isShowLoading)
    }

    private fun load() {
        p++
        myCollGoods(p)
    }


    private fun myCollGoods(p: Int, isShowLoading: Boolean = false) {
        val params = mutableMapOf<String, String?>()
        params["member_id"] = UserRepository.user.member_id
        params["p"] = p.toString()
        requestData(Urls.Center.MY_COLL_GOODS,
            params,
            resultClass = MyCollGoodsData::class.java,
            isShowLoading = isShowLoading,
            result = {
                if (1 == p) items.clear()
                it.list?.forEach {
                    items += MyFavoriteItemModel(this@MyFavoriteModel, ObservableField(it))
                }
            },
            finish = {
                stopRefreshOrLoadSingleLiveEvent.call()
            })
    }
}